package org.moonlight.jvm.classfile.attribute;

import lombok.Getter;
import org.moonlight.jvm.classfile.ClassReader;

/**
 * InnerClasses记录当前类的所有内部类。当前类需要记录的内部类的算法如下：
 *    1. 当前类中定义的内部类，包括方法中定义的类。
 *    2. 如果当前类本身是内部类，则还要记录当前类的外部类，直到外部类不是一个内部类。
 * 其结构定义如下:
 *    InnerClasses_attribute {
 *        u2 attribute_name_index;
 *        u4 attribute_length;
 *        u2 number_of_classes;
 *        {
 *            u2 inner_class_info_index;
 *            u2 outer_class_info_index;
 *            u2 inner_name_index;
 *            u2 inner_class_access_flags;
 *        } classes[number_of_classes];
 *    }
 *
 * @author Moonlight
 * @createTime 2023/8/15 17:45
 **/
@Getter
public class InnerClassesAttribute implements AttributeInfo {

    private InnerClassInfo[] classes;

    @Override
    public void readInfo(ClassReader reader) {
        int numOfClasses = reader.readUint16();
        InnerClassInfo[] classes = new InnerClassInfo[numOfClasses];
        for (int i = 0; i < numOfClasses; i++) {
            classes[i] = new InnerClassInfo(
                    reader.readUint16(), reader.readUint16(),reader.readUint16(),reader.readUint16()
            );
        }
        this.classes = classes;
    }

    @Getter
    static class InnerClassInfo {
        private final int innerClassInfoIdx;
        private final int outerClassInfoIdx;
        private final int innerNameIdx;
        private final int innerClassAccessFlags;

        InnerClassInfo(int innerClassInfoIdx, int outerClassInfoIdx, int innerNameIdx, int innerClassAccessFlags) {
            this.innerClassInfoIdx = innerClassInfoIdx;
            this.outerClassInfoIdx = outerClassInfoIdx;
            this.innerNameIdx = innerNameIdx;
            this.innerClassAccessFlags = innerClassAccessFlags;
        }

    }

}
